<script setup lang="ts">
import type CheckboxOption from './CheckboxOption.ts'


const props = defineProps({
  label: String,
  modelValue: {
    type: Array as () => (string | number)[],
    default: () => []
  },
  options: {
    type: Array as () => CheckboxOption[],
    default: () => []
  },
  disabled: Boolean,
  direction: {
    type: String as () => 'row' | 'column',
    default: 'row'
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

function isDisabled(option: CheckboxOption) {
  return props.disabled || option.disabled
}

function isChecked(option: CheckboxOption) {
  return props.modelValue.includes(option.value)
}

function toggle(option: CheckboxOption) {
  if (isDisabled(option)) return

  const newValue = [...props.modelValue]
  const index = newValue.indexOf(option.value)

  if (index > -1) {
    newValue.splice(index, 1)
  } else {
    newValue.push(option.value)
  }

  emit('update:modelValue', newValue)
  emit('change', newValue)
}
</script>

<template>
  <div class="checkbox-group" :class="`direction-${props.direction}`">
    <span class="checkbox-group-label">{{ label }}</span>
    <div
        v-for="option in options"
        :key="option.value"
        class="checkbox-item"
        :class="{ checked: isChecked(option), disabled: isDisabled(option) }"
        @click="toggle(option)"
    >
      <span class="checkbox-box">
        <span v-if="isChecked(option)" class="checkbox-check"/>
      </span>
      <span class="checkbox-label">{{ option.label }}</span>
    </div>
  </div>
</template>

<style scoped>
.checkbox-group {
  display: flex;
  padding: 10px;
  gap: 8px;
}

.checkbox-group.direction-column {
  flex-direction: column;
}

.checkbox-group.direction-row {
  flex-direction: row;
}

.checkbox-group-label {
  font-weight: bold;
}

.checkbox-item {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.checkbox-item.disabled {
  cursor: not-allowed;
  opacity: 0.6;
}

.checkbox-box {
  width: 16px;
  height: 16px;
  border: 1px solid #999;
  border-radius: 2px;
  margin-right: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.checkbox-check {
  width: 10px;
  height: 10px;
  background-color: #409EFF;
  border-radius: 2px;
}

.checkbox-item.checked .checkbox-box {
  border-color: #409EFF;
}
</style>
